from operator import is_
from django.shortcuts import render
from .forms import PostSearchForm
from .models import Book
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank


def post_search(request):
    form = PostSearchForm
    results = []
    if 'q' in request.GET:
        form = PostSearchForm(request.GET)
        if form.is_valid():
            q = form.cleaned_data['q']
            print(q)
            print(form.cleaned_data)
        results = Book.objects.filter(title__search=q)
        print(results.explain(analyze=True))
        # results = Book.objects.annotate(
        #     search=SearchVector('title', 'authors')
        # ).filter(search=q)
        # vector = SearchVector('title', 'authors')
        vector = SearchVector('title', weight='B') + \
            SearchVector('authors', weight='A')
        query = SearchQuery(q)
        results = Book.objects.annotate(
            rank=SearchRank(vector=vector, query=query)
        ).order_by('-rank')
    return render(request, 'index.html', {'form': form, 'results': results})
